package com.qishi.mySocket;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

public class MyResponse {

    private static final int BUFFER_SIZE =1024;

    MyRequest request;

    OutputStream output;

    public MyResponse(OutputStream outputStream) {
        this.output = outputStream;
    }

    public void setRequest(MyRequest request) {
        this.request = request;
    }

    public void sendStaticResource() throws IOException {
        byte[] bytes = new byte[BUFFER_SIZE];
        FileInputStream fis = null;
        try {
            //根据请求的uri来找寻跟目录下webRoot目录下的相对应的文件
            File file = new File(MyHttpServer.WEB_ROOT, request.getUri());
            if(file.exists()) {
                fis = new FileInputStream(file);
                int ch = fis.read(bytes,0,BUFFER_SIZE);
                while (ch != -1) {
                    output.write(bytes,0,ch);
                    ch =fis.read(bytes,0,BUFFER_SIZE);
                }
            }else {
                //如果文件不存在
                String errorMessage = "HTTP/1.1 404 File Not Found\r\n" +
                        "Content-Type: text/html\r\n" +
                        "Content-Length: 23\r\n" +
                        "\r\n" +
                        "<h1>File Not Found</h1>";
                output.write(errorMessage.getBytes());
            }

        }catch (Exception e) {
            System.out.println(e.toString());
        }finally {
            if(fis != null) {
                fis.close();
            }
        }
    }

}
